package com.liuyang.controller;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapBuilder;
import com.liuyang.common.Result;
import com.liuyang.entity.News;
import com.liuyang.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者:caleb
 * @since 2022-03-02
 */
@RestController
@RequestMapping("/system/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    // 富文本编辑框图片上传功能
    @PostMapping("/uploadNewsImage")
    public Result uploadNewsImage(@RequestParam("file") MultipartFile file) {
        try {
            File dir = new File("D:\\upload\\news");
            if(!dir.exists()) {
                dir.mkdirs();
            }
            Snowflake snowflake = new Snowflake(2,3);
            String id = snowflake.nextIdStr();
            String fileName = file.getOriginalFilename();
            fileName = id + fileName.substring(fileName.indexOf("."));
            file.transferTo(new File("D:\\upload\\news\\" + fileName));

            MapBuilder<String, String> mapBuilder = MapBuilder.create();
            Map<String, String> mapImg = mapBuilder.put("src", "../news/" + fileName).put("title", fileName).map();
            return Result.succ(0, "", mapImg);
        } catch (IOException e) {
            return Result.succ("图片上传失败");
        }
    }

    // 新增新闻资讯
    @PostMapping("/insertNewsInfo")
    public Result insertNewsInfo(News news) {
        Snowflake snowflake = new Snowflake(2,3);
        String id = snowflake.nextIdStr();
        news.setId(id);
        newsService.save(news);
        return Result.succ("新增新闻资讯成功");
    }

    // 分页获取新闻资讯
    @PostMapping("/getNewsInfo")
    public Result getNewsInfo(int page, int limit) {
        Map<String, Object> newsInfo = newsService.getNewsInfo(page, limit);
        return Result.succ(200, "", newsInfo);
    }

    // 查看新闻资讯
    @PostMapping("/getNewsInfoById")
    public Result getNewsInfoById(String id) {
        News news = newsService.getById(id);
        return Result.succ(news);
    }
}
